<!--
@description ：公用分组组件
@createTime ：2024/04/16
-->

<template>
  <div>
    <el-tree ref="tree" v-loading="treeLoading" :data="treeData" :expand-on-click-node="false" :props="treeProps"
             default-expand-all highlight-current @node-click="handleNodeClick">
      <div slot-scope="{ node, data }" class="custom-tree-node">
        <el-tooltip v-if="node.label.length > 8" :content="node.label" effect="dark" placement="bottom">
          <span class="label-info">{{ node.label }}</span>
        </el-tooltip>
        <span v-else>{{ node.label }}</span>
        <el-dropdown v-if="data.id" trigger="click">
          <i class="el-icon-more" @click.stop></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item style="color: #082AFF" @click.stop.native="itemEdit(node, data)">修改名称
            </el-dropdown-item>
            <el-dropdown-item :disabled="!data.delFlag" :style="`color: ${ !data.delFlag ? '#cccccc' : '#082AFF' }`" @click.stop.native="itemDel(node, data)">删除分组
            </el-dropdown-item>
            <el-dropdown-item :disabled="data.sortId == '1'" :style="`color: ${ data.sortId == '1' ? '#cccccc' : '#082AFF' }`"
                              @click.stop.native="itemSortEdit(node, data, 'up')">上移
            </el-dropdown-item>
            <el-dropdown-item :disabled="data.sortId == groupTotal" :style="`color: ${ data.sortId == groupTotal ? '#cccccc' : '#082AFF' }`"
                              @click.stop.native="itemSortEdit(node, data, 'down')">下移
            </el-dropdown-item>
            <el-dropdown-item :disabled="data.sortId == '1'" :style="`color: ${ data.sortId == '1' ? '#cccccc' : '#082AFF' }`"
                              @click.stop.native="itemSortEdit(node, data,'top')">置顶
            </el-dropdown-item>
            <el-dropdown-item :disabled="data.sortId == groupTotal" :style="`color: ${ data.sortId == groupTotal ? '#cccccc' : '#082AFF' }`"
                              @click.stop.native="itemSortEdit(node, data,'bot')">置底
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span v-if="!data.id" class="add" style="color: #082AFF" @click.stop="handleAddItem">
                <i class="el-icon-circle-plus-outline"></i>&nbsp;添加
              </span>
      </div>
    </el-tree>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :title="treeForm.id ? '编辑' : '添加' + '分组'"
               :visible.sync="treeDialogVisible" width="400px">
      <el-form ref="treeForm" :model="treeForm" label-width="120px">
        <el-form-item label="请输入分组名称">
          <el-input v-model="treeForm.name" maxlength="32" placeholder="请输入" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button plain type="info" @click="treeDialogVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除分组确认 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :visible.sync="delVisible"
               title="删除分组确认" width="400px">
      <span>确认删除该分组吗？</span>
      <div slot="footer">
        <el-button plain type="info" @click="delVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeDelSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 数据移入新分组 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :visible.sync="delToReVisible" append-to-body
               title="移动分组" width="460px">
      <div class="delToRe_info">
        <i class="el-icon-warning" style="color: #082AFF;margin-right: 6px"></i>
        <span>{{ `该分组共有${delGroupTotal}条数据，请移入其他分组` }}</span>
      </div>
      <el-form ref="delToReForm" :model="delToReForm" :rules="delToReRules" label-width="160px">
        <el-form-item label="请选择要移入的分组:" prop="newId">
          <el-select v-model="delToReForm.newId" clearable placeholder="请选择分组">
            <el-option v-for="item in newGroupList" :key="item.id"
                       :label="item.name" :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button plain type="info" @click="delToReVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeDelToReSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {categoryAddCorp, categoryDelCorp, categoryEditCorp, categoryList} from "@/api/article/group";
import {delRadarCategory, queryRadarCount, sortRadarCategory} from "@/api/visitorRadar";

export default {
  name: "grouping", //页面名称，必填
  props: {
    /**
     * mediaType  分组类型   14- 敏感词
     * levelType  分组级别   0-企业  1-个人
    **/
    mediaType: {
      type: String,
      default: '0',
    },
    levelType: {
      type: String,
      default: '0',
    },
    showSelectName: {
      type: Boolean,
      default: false,
    },
  },
  components: {},
  data() {
    return {
      treeForm: {
        id: '',
        name: '',
      },
      treeData: [
        {
          id: '',
          name: '全部',
          parentId: 0,
          hasParent: false,
          hasChildren: true,
          children: []
        },
      ],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      groupId: '',
      treeLoading: false,
      treeDialogVisible: false, // 新增/编辑分组
      delVisible: false, // 分组删除确认
      delTable: false, // 表格删除确认
      delToReVisible: false, //移动分组弹窗
      delToReForm: {
        newId: '',
      },
      newGroupList: [], // 移动分组的数据
      delToReRules: {
        newId: {
          required: true, message: '要移入的分组不能为空', trigger: 'change'
        },
      },
      delGroupTotal: 0,
      currentGroupId: '',
      currentRow: null,
    }
  },
  watch: {},
  methods: {
    // 获取分组数据
    getNodeFn() {
      let params = {
        levelType: this.levelType,
        mediaType: this.mediaType,
      }
      categoryList(params).then(res => {
        if (res.code == 200) {
          this.groupTotal = res.data ? res.data.length : 0
          this.$set(this.treeData[0], 'children', res.data)
          this.$emit('updateNodeToQuery', '')
          this.$emit('updateGroupData', res.data)
          this.groupId = ''
          this.currentGroupId = ''
        }
      })
    },
    // 分组点击事件
    handleNodeClick(data) {
      console.log(data, '分组排序事件')
      this.groupId = data.id
      this.currentGroupId = data.id
      this.$emit('updateNodeToQuery', this.groupId)
    },
    // 编辑分组
    itemEdit(node, data) {
      console.log(node, data, '修改分组')
      this.treeForm = data
      this.treeDialogVisible = true
    },
    // 删除分组
    itemDel(node, data) {
      if (!data.delFlag) return
      console.log(node, data, '删除分组')
      this.treeForm = data
      this.delVisible = true
    },
    // 新增/修改分组提交
    treeSubmit() {
      this.$refs.treeForm.validate(async (valid) => {
        if (valid) {
          const params = {
            id: this.treeForm.id || null,
            levelType: this.levelType,
            mediaType: this.mediaType,
            name: this.treeForm.name
          }
          if (this.treeForm.id) {
            categoryEditCorp(params).then(res => {
              this.treeDialogVisible = false
              this.$message.success('分组编辑成功')
              this.getNodeFn()
            })
          } else {
            categoryAddCorp(params).then(res => {
              this.treeDialogVisible = false
              this.$message.success('分组添加成功')
              this.getNodeFn()
            })
          }
        } else {
          return false
        }
      })
    },
    // 数组排序修改
    itemSortEdit(node, data, flag) {
      console.log(flag, 'flag')
      let arr = JSON.parse(JSON.stringify(this.treeData[0].children))
      if (flag == 'up') {
        // 上移
        // 定义要交换位置的对象索引
        let index1 = +data.sortId - 1;
        let index2 = +data.sortId - 2;
        // 交换位置
        let temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
        console.log(arr, '上移', index1, index2)
      } else if (flag == 'down') {
        // 下移
        // 定义要交换位置的对象索引
        let index1 = +data.sortId - 1;
        let index2 = +data.sortId;
        // 交换位置
        let temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
        console.log(arr, '下移', index1, index2)
      } else if (flag == 'top') {
        // 置顶
        // 将元素移动到最前面
        let index = +data.sortId - 1;
        let element = arr.splice(index, 1)[0]; // 先将元素从数组中删除并保存到变量中
        arr.unshift(element); // 再将元素插入到数组的最前面
        console.log(arr, '置顶')
      } else if (flag == 'bot') {
        // 置底
        // 将元素移动到最后面
        let index = +data.sortId - 1;
        let element = arr.splice(index, 1)[0]; // 先将元素从数组中删除并保存到变量中
        arr.push(element); // 再将元素插入到数组的最后面
        console.log(arr, '置底')
      }
      arr.forEach((item, ind) => {
        item.sortId = String(ind + 1)
      })
      const idList = arr.map(item => item.id)
      this.treeLoading = true
      sortRadarCategory({idList: idList}).then(res => {
        if (res.code == 200) this.getNodeFn()
        this.treeLoading = false
      }).catch(() => {
        this.treeLoading = false
      })
    },
    // 删除分组提交
    treeDelSubmit() {
      queryRadarCount({id: this.treeForm.id}).then(res => {
        if (res.code == 200) {
          if (res.data.delFlag == true) {
            categoryDelCorp(this.treeForm.id).then(res => {
              if (res.code == 200) {
                this.$message.success('删除成功')
                this.getNodeFn()
                this.delVisible = false
              }
            })
          } else {
            this.delGroupTotal = res.data.radarCount || 0
            this.currentGroupId = this.treeForm.id
            this.delToReVisible = true
            this.$refs.delToReForm.resetFields()
            this.newGroupList = this.treeData[0]?.children.filter(item => item.id != this.treeForm.id)
            this.delToReForm.newId = this.newGroupList ? this.newGroupList[0]?.id : ''

          }
        }
      })
    },
    // 添加分组
    handleAddItem() {
      this.treeForm = {
        id: '',
        name: '',
      }
      this.treeDialogVisible = true
    },
    // 移动分组
    treeDelToReSubmit() {
      this.$refs.delToReForm.validate((valid) => {
        if (valid) {
          let params = {
            id: this.currentGroupId,
            newId: this.delToReForm.newId
          }
          delRadarCategory(params).then(res => {
            if (res.code == 200) {
              this.$message.success('分组迁移成功')
              this.currentGroupId = ''
              this.delToReVisible = false
              this.delVisible = false
              this.getNodeFn()
            }
          })
        }
      })
    },
    // 重置分组查询
    resetNode(){
      this.groupId = ''
      this.currentGroupId = ''
    }
  },
  mounted() {
    this.getNodeFn()
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

::v-deep {
  .el-tabs__header {
    margin: 0;
  }

  .el-tree {
    padding: 10px 10px 0 10px;
  }

  .el-tree-node__content {
    height: 35px;
    padding-left: 10px !important;
  }
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-right: 10px;
  font-size: 12px;

  .label-info {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

</style>
